<?php

namespace App\BO\Wechat;

use App\BO\Wechat\Meta\WechatPayResultMeta;

class WechatSign
{
    /**
     * Generate wechat sign.
     *
     * @param string $key
     * @param WechatPayResultMeta $payInfo
     * @return string
     */
    public static function generateSign(string $key, WechatPayResultMeta $payInfo)
    {
        $data = [
            'appId'     => $payInfo->getAppId(),
            'timeStamp' => $payInfo->getTimeStamp(),
            'nonceStr'  => $payInfo->getNonceStr(),
            'package'   => $payInfo->getPackage(),
            'signType'  => 'MD5',
        ];

        ksort($data);

        $string = md5(self::getSignContent($data) . '&key=' . $key);

        return strtoupper($string);
    }

    /**
     * Generate sign content.
     *
     * @author yansongda <me@yansongda.cn>
     *
     * @param array $data
     *
     * @return string
     */
    private static function getSignContent($data): string
    {
        $buff = '';

        foreach ($data as $k => $v) {
            $buff .= ($k != 'sign' && $v != '' && !is_array($v)) ? $k . '=' . $v . '&' : '';
        }

        return trim($buff, '&');
    }
}
